<template>
  <div class="notification-settings-container">
    <el-card v-loading="loading">
      <template #header>
        <div class="card-header">
          <span class="header-title">
            <IconifyIconOffline icon="ep:bell" />
            通知设置
          </span>
        </div>
      </template>

      <div class="settings-content">
        <!-- 通知类型开关 -->
        <div class="settings-section">
          <div class="section-title">通知类型</div>
          <div class="settings-list">
            <div class="setting-item">
              <div class="setting-info">
                <div class="setting-label">
                  <IconifyIconOffline icon="ep:user-filled" />
                  关注通知
                </div>
                <div class="setting-desc">有用户关注你时收到通知</div>
              </div>
              <el-switch
                v-model="settings.followEnabled"
                @change="handleSettingChange('followEnabled', $event)"
              />
            </div>

            <div class="setting-item">
              <div class="setting-info">
                <div class="setting-label">
                  <IconifyIconOffline icon="ep:heart-filled" />
                  点赞通知
                </div>
                <div class="setting-desc">文章或评论被点赞时收到通知</div>
              </div>
              <el-switch
                v-model="settings.likeEnabled"
                @change="handleSettingChange('likeEnabled', $event)"
              />
            </div>

            <div class="setting-item">
              <div class="setting-info">
                <div class="setting-label">
                  <IconifyIconOffline icon="ep:star-filled" />
                  收藏通知
                </div>
                <div class="setting-desc">文章被收藏时收到通知</div>
              </div>
              <el-switch
                v-model="settings.collectEnabled"
                @change="handleSettingChange('collectEnabled', $event)"
              />
            </div>

            <div class="setting-item">
              <div class="setting-info">
                <div class="setting-label">
                  <IconifyIconOffline icon="ep:chat-line-round" />
                  评论通知
                </div>
                <div class="setting-desc">文章被评论时收到通知</div>
              </div>
              <el-switch
                v-model="settings.commentEnabled"
                @change="handleSettingChange('commentEnabled', $event)"
              />
            </div>

            <div class="setting-item">
              <div class="setting-info">
                <div class="setting-label">
                  <IconifyIconOffline icon="ep:chat-dot-round" />
                  回复通知
                </div>
                <div class="setting-desc">评论被回复时收到通知</div>
              </div>
              <el-switch
                v-model="settings.replyEnabled"
                @change="handleSettingChange('replyEnabled', $event)"
              />
            </div>

            <div class="setting-item">
              <div class="setting-info">
                <div class="setting-label">
                  <IconifyIconOffline icon="ep:position" />
                  @提及通知
                </div>
                <div class="setting-desc">被@提及时收到通知</div>
              </div>
              <el-switch
                v-model="settings.mentionEnabled"
                @change="handleSettingChange('mentionEnabled', $event)"
              />
            </div>

            <div class="setting-item">
              <div class="setting-info">
                <div class="setting-label">
                  <IconifyIconOffline icon="ep:bell-filled" />
                  系统通知
                </div>
                <div class="setting-desc">接收系统通知和公告</div>
              </div>
              <el-switch
                v-model="settings.systemEnabled"
                @change="handleSettingChange('systemEnabled', $event)"
              />
            </div>
          </div>
        </div>

        <!-- 免打扰模式 -->
        <div class="settings-section">
          <div class="section-title">免打扰模式</div>
          <div class="settings-list">
            <div class="setting-item">
              <div class="setting-info">
                <div class="setting-label">
                  <IconifyIconOffline icon="ep:moon-night" />
                  开启免打扰
                </div>
                <div class="setting-desc">在指定时间段内不接收通知推送</div>
              </div>
              <el-switch
                v-model="settings.doNotDisturbEnabled"
                @change="handleDoNotDisturbToggle"
              />
            </div>

            <div class="time-range-picker">
              <el-time-picker
                v-model="doNotDisturbStartTime"
                placeholder="开始时间"
                format="HH:mm:ss"
                value-format="HH:mm:ss"
                :disabled="!settings.doNotDisturbEnabled"
                @change="handleTimeChange"
              />
              <span class="time-separator">至</span>
              <el-time-picker
                v-model="doNotDisturbEndTime"
                placeholder="结束时间"
                format="HH:mm:ss"
                value-format="HH:mm:ss"
                :disabled="!settings.doNotDisturbEnabled"
                @change="handleTimeChange"
              />
            </div>
          </div>
        </div>

        <!-- 高级设置 -->
        <div class="settings-section">
          <div class="section-title">高级设置</div>
          <div class="settings-list">
            <div class="setting-item">
              <div class="setting-info">
                <div class="setting-label">
                  <IconifyIconOffline icon="ep:collection" />
                  通知聚合
                </div>
                <div class="setting-desc">相同类型的通知会聚合显示</div>
              </div>
              <el-switch
                v-model="settings.notificationAggregationEnabled"
                @change="
                  handleSettingChange('notificationAggregationEnabled', $event)
                "
              />
            </div>

            <div class="setting-item">
              <div class="setting-info">
                <div class="setting-label">
                  <IconifyIconOffline icon="ep:connection" />
                  实时推送
                </div>
                <div class="setting-desc">通过WebSocket实时接收通知</div>
              </div>
              <el-switch
                v-model="settings.websocketEnabled"
                @change="handleSettingChange('websocketEnabled', $event)"
              />
            </div>

            <div class="setting-item">
              <div class="setting-info">
                <div class="setting-label">
                  <IconifyIconOffline icon="ep:message" />
                  邮件通知
                </div>
                <div class="setting-desc">通过邮件接收重要通知</div>
              </div>
              <el-switch
                v-model="settings.emailNotificationEnabled"
                @change="
                  handleSettingChange('emailNotificationEnabled', $event)
                "
              />
            </div>
          </div>
        </div>

        <!-- 快捷操作 -->
        <div class="settings-section">
          <div class="section-title">快捷操作</div>
          <div class="quick-actions">
            <el-button
              type="primary"
              :loading="actionLoading"
              @click="handleEnableAll"
            >
              <IconifyIconOffline icon="ep:check" />
              一键开启所有通知
            </el-button>
            <el-button
              type="warning"
              :loading="actionLoading"
              @click="handleDisableAll"
            >
              <IconifyIconOffline icon="ep:close" />
              一键关闭所有通知
            </el-button>
            <el-button
              type="info"
              :loading="actionLoading"
              @click="handleReset"
            >
              <IconifyIconOffline icon="ep:refresh" />
              恢复默认设置
            </el-button>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";
import type { NotificationSettings } from "@/types/notification-settings";
import {
  getNotificationSettingsApi,
  updateNotificationSettingsApi,
  resetNotificationSettingsApi,
  enableAllNotificationsApi,
  disableAllNotificationsApi,
  setDoNotDisturbApi
} from "@/api/notification-settings";

// 响应式数据
const loading = ref(false);
const actionLoading = ref(false);
const settings = ref<NotificationSettings>({
  followEnabled: true,
  likeEnabled: true,
  commentEnabled: true,
  replyEnabled: true,
  mentionEnabled: true,
  systemEnabled: true,
  collectEnabled: true,
  doNotDisturbEnabled: false,
  doNotDisturbStart: "22:00:00",
  doNotDisturbEnd: "08:00:00",
  notificationAggregationEnabled: true,
  websocketEnabled: true,
  emailNotificationEnabled: false,
  emailFollowEnabled: false,
  emailCommentEnabled: false,
  emailReplyEnabled: false,
  emailMentionEnabled: false,
  emailSystemEnabled: true
});

const doNotDisturbStartTime = ref("");
const doNotDisturbEndTime = ref("");

// 加载通知设置
const loadSettings = async () => {
  loading.value = true;
  try {
    const response = await getNotificationSettingsApi();
    if (response.code === 200 && response.data) {
      settings.value = response.data;
      doNotDisturbStartTime.value = response.data.doNotDisturbStart;
      doNotDisturbEndTime.value = response.data.doNotDisturbEnd;
    }
  } catch (error) {
    console.error("加载通知设置失败:", error);
    ElMessage.error("加载通知设置失败");
  } finally {
    loading.value = false;
  }
};

// 处理设置项变更
const handleSettingChange = async (key: string, value: boolean) => {
  try {
    const params = {
      [key]: value ? 1 : 0
    };
    const response = await updateNotificationSettingsApi(params);
    if (response.code === 200) {
      ElMessage.success("设置已更新");
    } else {
      ElMessage.error(response.message || "更新失败");
      // 恢复原值
      (settings.value as any)[key] = !value;
    }
  } catch (error) {
    console.error("更新设置失败:", error);
    ElMessage.error("更新设置失败");
    // 恢复原值
    (settings.value as any)[key] = !value;
  }
};

// 处理免打扰开关切换
const handleDoNotDisturbToggle = async (value: boolean) => {
  // 如果开启免打扰，但没有设置时间，使用默认时间
  if (value) {
    if (!doNotDisturbStartTime.value) {
      doNotDisturbStartTime.value = "22:00:00";
    }
    if (!doNotDisturbEndTime.value) {
      doNotDisturbEndTime.value = "08:00:00";
    }
  }

  try {
    const response = await setDoNotDisturbApi({
      enabled: value ? 1 : 0,
      startTime: value ? doNotDisturbStartTime.value : undefined,
      endTime: value ? doNotDisturbEndTime.value : undefined
    });

    if (response.code === 200) {
      ElMessage.success(value ? "已开启免打扰模式" : "已关闭免打扰模式");
    } else {
      ElMessage.error(response.message || "操作失败");
      settings.value.doNotDisturbEnabled = !value;
    }
  } catch (error) {
    console.error("设置免打扰模式失败:", error);
    ElMessage.error("操作失败");
    settings.value.doNotDisturbEnabled = !value;
  }
};

// 处理时间变更
const handleTimeChange = async () => {
  if (!settings.value.doNotDisturbEnabled) return;

  if (!doNotDisturbStartTime.value || !doNotDisturbEndTime.value) {
    ElMessage.warning("请设置完整的时间段");
    return;
  }

  try {
    const response = await setDoNotDisturbApi({
      enabled: 1,
      startTime: doNotDisturbStartTime.value,
      endTime: doNotDisturbEndTime.value
    });

    if (response.code === 200) {
      ElMessage.success("免打扰时间段已更新");
      settings.value.doNotDisturbStart = doNotDisturbStartTime.value;
      settings.value.doNotDisturbEnd = doNotDisturbEndTime.value;
    } else {
      ElMessage.error(response.message || "更新失败");
    }
  } catch (error) {
    console.error("更新免打扰时间段失败:", error);
    ElMessage.error("更新失败");
  }
};

// 一键开启所有通知
const handleEnableAll = async () => {
  actionLoading.value = true;
  try {
    const response = await enableAllNotificationsApi();
    if (response.code === 200) {
      ElMessage.success("已开启所有通知");
      await loadSettings();
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("开启所有通知失败:", error);
    ElMessage.error("操作失败");
  } finally {
    actionLoading.value = false;
  }
};

// 一键关闭所有通知
const handleDisableAll = async () => {
  actionLoading.value = true;
  try {
    const response = await disableAllNotificationsApi();
    if (response.code === 200) {
      ElMessage.success("已关闭所有通知");
      await loadSettings();
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("关闭所有通知失败:", error);
    ElMessage.error("操作失败");
  } finally {
    actionLoading.value = false;
  }
};

// 恢复默认设置
const handleReset = async () => {
  actionLoading.value = true;
  try {
    const response = await resetNotificationSettingsApi();
    if (response.code === 200) {
      ElMessage.success("已恢复默认设置");
      await loadSettings();
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("恢复默认设置失败:", error);
    ElMessage.error("操作失败");
  } finally {
    actionLoading.value = false;
  }
};

// 组件挂载时加载设置
onMounted(() => {
  loadSettings();
});
</script>

<style scoped lang="scss">
// 移动端适配
@media screen and (width <= 768px) {
  .notification-settings-container {
    padding: 0 12px;

    .settings-content {
      .settings-section {
        .settings-list {
          .setting-item {
            flex-direction: column;
            gap: 12px;
            align-items: flex-start;
          }

          .time-range-picker {
            flex-direction: column;
            gap: 8px;

            .el-time-picker {
              width: 100%;
            }
          }
        }

        .quick-actions {
          flex-direction: column;

          .el-button {
            width: 100%;
          }
        }
      }
    }
  }
}

.notification-settings-container {
  max-width: 900px;
  padding: 0 20px;
  margin: 20px auto;

  .card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .header-title {
      display: flex;
      gap: 8px;
      align-items: center;
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }
  }

  .settings-content {
    .settings-section {
      margin-bottom: 32px;

      &:last-child {
        margin-bottom: 0;
      }

      .section-title {
        margin-bottom: 16px;
        font-size: 16px;
        font-weight: 600;
        color: #303133;
      }

      .settings-list {
        .setting-item {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 16px 0;
          border-bottom: 1px solid #f0f0f0;

          &:last-child {
            border-bottom: none;
          }

          .setting-info {
            flex: 1;

            .setting-label {
              display: flex;
              gap: 8px;
              align-items: center;
              margin-bottom: 4px;
              font-size: 15px;
              font-weight: 500;
              color: #303133;
            }

            .setting-desc {
              font-size: 13px;
              color: #909399;
            }
          }
        }

        .time-range-picker {
          display: flex;
          gap: 12px;
          align-items: center;
          padding: 12px 16px;
          margin-top: 8px;
          background-color: #f5f7fa;
          border-radius: 8px;

          .time-separator {
            font-size: 14px;
            color: #909399;
          }

          :deep(.el-input__wrapper) {
            background-color: #fff;
          }

          :deep(.el-time-picker) {
            width: 180px;
          }

          :deep(.is-disabled) {
            cursor: not-allowed;
            opacity: 0.6;
          }
        }
      }

      .quick-actions {
        display: flex;
        flex-wrap: wrap;
        gap: 12px;

        .el-button {
          display: flex;
          gap: 6px;
          align-items: center;
        }
      }
    }
  }
}
</style>
